import org.springframework.context.MessageSource
import org.springframework.validation.FieldError

class RemoteValidateController {
    GroovyClassLoader gcl = new GroovyClassLoader()
    MessageSource messageSource

    def index = {
        Class modelClass = gcl.loadClass(params.model)
        def model = modelClass.newInstance()

        String fieldName = params.field
        model."$fieldName" = params.value

        List messageList = []
        if (!model.validate()) {
            List fieldErrors = model.errors.getFieldErrors(fieldName)
            for (FieldError fieldError: fieldErrors) {
                String message = messageSource.getMessage(fieldError, request.getLocale())
                messageList << message
            }
        }

        if (params.renderAs && params.renderAs == 'list') {
            render(contentType: "text/plain", encoding: "UTF-8") {
                ul {
                    messageList.each {
                        li(it)
                    }
                }
            }
        } else if (messageList) {
            render(text: messageList[0], contentType: "text/plain", encoding: "UTF-8")
        } else {
            render(text: '', contentType: "text/plain", encoding: "UTF-8")
        }
    }
}
